var express = require('express');
var router = express.Router();
const db = require('../db/index');

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});

// 登录功能
router.post('/login', function(req, res, next) {
  const { username, password } = req.body;
  const sql = 'select * from users where username=? and password=?';
  db.query(sql, [username, password], function(err, result) {
    if (err) {
      return res.send({
        code: 500,
        message: '登录失败'
      });
    }
    if (result.length === 0) {
      return res.send({
        code: 400,
        message: '用户名或密码错误'
      });
    }
    res.send({
      code: 200,
      message: '登录成功',
      success: true
    })
  })
})

// 注册功能
router.post('/register', function(req, res, next) {
  const { username, password } = req.body;
  const sql = 'insert into users (username, password) values (?, ?)';
  db.query(sql, [username, password], function(err, result) {
    if (err) {
      return res.send({
        code: 500,
        message: '注册失败'
      });
    }
    res.send({
      code: 200,
      message: '注册成功',
      success: true
    })
  })
})

module.exports = router;
